//
//  TodoService.m
//  DoIT
//
//  Created by 葛欣 on 14/11/22.
//  Copyright (c) 2014年 gex. All rights reserved.
//

#import "TodoService.h"
#import "Singleton.h"
#import "Todo.h"
#import "DbManager.h"
#import "NSDate+Utils.h"

@implementation TodoService
singleton_implementation(TodoService);

/**
 *  添加
 *
 */
-(void)addTodo:(Todo *)todo{
    NSArray *args = [NSArray arrayWithObjects:todo.content, todo.status,todo.creationTime,todo.modifyTime, nil];
    [[DbManager sharedDbManager] executeNonQuery:@"INSERT INTO todo (content,status,creationTime,modifyTime) VALUES(?,?,?,?)" withArgumentsInArray:args];
}
/**
 *  删除
 */
-(void)removeTodo:(Todo *)todo{
    NSArray *args = [NSArray arrayWithObjects:todo.Id,nil];
    [[DbManager sharedDbManager] executeNonQuery:@"DELETE FROM todo WHERE Id=?" withArgumentsInArray:args];
}
/**
 *  修改
 *
 */
-(void)modifyTodo:(Todo *)todo{
    todo.modifyTime = [NSDate dateLocal];
    NSArray *args = @[todo.content,todo.status,todo.modifyTime,todo.Id];
    [[DbManager sharedDbManager] executeNonQuery:@"UPDATE todo set content=?,status=?,modifyTime=? WHERE Id=?" withArgumentsInArray:args];
}
/**
 *  根据编号取得
 */
-(Todo *)getTodoById:(int)Id{
    Todo *todo=nil;
    NSArray *args = [NSArray arrayWithObjects:[NSNumber numberWithInt:Id],nil];
    NSArray *rows=  [[DbManager sharedDbManager] executeQuery:@"SELECT Id, content,status,creationTime FROM todo WHERE Id='%i'" withArgumentsInArray:args];
    if (rows&&rows.count>0) {
        todo=[[Todo alloc] initWithDictionary:rows[0]];
    }
    return todo;
}
/**
 *  取得所有在做todo
 *
 */
-(NSArray *)getAllTodoByStatus:(TodoStatus)status{
    NSMutableArray *array=[NSMutableArray array];
    NSArray *rows= [[DbManager sharedDbManager] executeQuery:@"SELECT Id, content,status,creationTime,modifyTime FROM todo WHERE status=? ORDER BY modifyTime DESC" withArgumentsInArray:@[[NSNumber numberWithInteger:status]]];
    for (NSDictionary *dic in rows) {
        Todo *todo=[[Todo alloc] initWithDictionary:dic];
        [array addObject:todo];
    }
    NSLog(@"todoes:%@",array);
    return array;
}
-(NSArray *)getAllTodoByStatus:(TodoStatus)status date:(NSDate *)date{
    NSMutableArray *array=[NSMutableArray array];
    NSArray *rows= [[DbManager sharedDbManager] executeQuery:@"SELECT Id, content,status,creationTime,modifyTime FROM todo WHERE status=? AND modifyTime>? AND modifyTime<? ORDER BY modifyTime DESC" withArgumentsInArray:@[[NSNumber numberWithInteger:status],[NSNumber numberWithDouble:[date timeIntervalSince1970]],[NSNumber numberWithDouble:[[date nextDate] timeIntervalSince1970]]]];
    for (NSDictionary *dic in rows) {
        Todo *todo=[[Todo alloc] initWithDictionary:dic];
        [array addObject:todo];
    }
    NSLog(@"todoes:%@",array);
    return array;
}
@end
